from rest_framework import serializers
from order.models import OrderModel,OrderDetailsModel
from coupon.models import CouponModel


class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderModel
        fields = ['user','id','order_no','total_price','total_count','order_status','pay_type','ordered_at']


    def create(self, validated_data):
        # 从请求上下文获取当前用户，并将 user_id 添加到订单数据中
        user = self.context['request'].user
        validated_data['user'] = user

        # 处理优惠券 ID
        user_coupon_id = validated_data.pop('user_coupon_id', None)

        # 创建订单对象
        order = OrderModel.objects.create(**validated_data)

        # 如果有 user_coupon_id，关联优惠券信息
        if user_coupon_id is not None:
            coupon = CouponModel.objects.filter(id=user_coupon_id).first()
            if coupon:
                order.coupon = coupon
                order.save()

        return order


class OrderDetailSerializer(serializers.ModelSerializer):
    course_id = serializers.IntegerField(source='course.id')
    course_name = serializers.CharField(source='course.name')
    course_cover = serializers.ImageField(source='course.course_cover')
    class Meta:
        model = OrderDetailsModel
        fields = ['id','course_id','course_name','course_cover','unit_price','quantity','total_price']
